import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    // 购物车数组
    cartList: uni.getStorageSync("cartList") || []
  },
  getters: {
    // 要购物的总数量
    allCount: state => {
      // this.cartList
      // this.$store.state.cartList
      let count = 0;
      state.cartList.forEach(goods => {
        if (goods.checked) {
          count += goods.count;
        }
      });
      return count
    },
       // 要支付的总价格
       allPrice(state) {
        let allPrice = 0;
        state.cartList.forEach((goods) => {
          if (goods.checked) {
            allPrice += goods.goods_price * goods.count;
          }
        });
        return allPrice;
      },
  },
  // 柜台人员
  mutations: {
    setCartList(state, cartList) {
      state.cartList = cartList;
      // 把数组存一份到本地存储中即可
      uni.setStorageSync("cartList", cartList);
    }
  }
});

export default store;